import md5 from 'js-md5';
import axios from 'axios';
import Config from './config.js'
import { ElMessage } from 'element-plus'
import {useRouter} from 'vue-router';
import QS from 'qs' // 引入qs模块，用来序列化post类型的数据
const router = useRouter();

axios.defaults.timeout = 10000;//设置请求超时

//判断是否生产环境
// if(Config.dev == 1){
// 	axios.defaults.baseURL = '/myApi/';//开发环境
// }else{
	axios.defaults.baseURL = Config.baseUrl;//生产环境
// }

axios.defaults.withCredentials=true;
//post请求头的设置
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

// 请求拦截器
axios.interceptors.request.use(
  config => {
	// 接口公共参数配置
	let lang = localStorage.getItem('lang') || 'zh';
	let token = localStorage.getItem('login') || JSON.stringify({id:''});
	let time = Date.parse(new Date())/1000;
	let publicParams = {
		lang:lang,
		token:JSON.parse(token).id,
		client:'admin',
	}
	publicParams.time = time;
	publicParams.sign = md5(time+100+'');
    if(config.method === 'post') {
        let data = QS.parse(config.data)
        config.data = QS.stringify({
			...publicParams,
            ...data
        })
    }
	if(config.method === 'get') {
        config.params = {
			...publicParams,
            ...config.params
        }
    }
	
	// 头部参数
	config.headers.token = 'token Not enabled' 
	
    return config;
  },
  error => {
    return Promise.error(error);
  }
)

// 响应拦截器
axios.interceptors.response.use(
    response => {
        switch (response.data.code) {
            case 200:
                return Promise.resolve(response);
            case 10001:
            case 10002:
            case 10003:
				ElMessage.error('请求验证失败，请重新登录后再试')
				localStorage.removeItem("login");
				router.push({path: "/login"})
				return Promise.resolve(response);
            default:
                return Promise.resolve(response);
        }
    },
    error => {
        return Promise.reject(error.response);
    }

);

/**
  * get方法，对应get请求
  * @param {String} url [请求的url地址]
  * @param {Object} params [请求时携带的参数]
  */
 function get(url, params){
    return new Promise((resolve, reject) =>{
        axios.get(url, {
            params:params
        })
        .then(res => {
            resolve(res.data);
        })
        .catch(err => {
            reject(err)
        })
    });
}

/**
  * post方法，对应post请求
  * @param {String} url [请求的url地址]
  * @param {Object} params [请求时携带的参数]
  */
function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, QS.stringify(params))
        .then(res => {
            resolve(res.data);
        })
        .catch(err => {
            reject(err)
        })
    });
}

export default {post,get}

